from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QTextEdit,
                             QPushButton, QHBoxLayout, QFileDialog,
                             QLabel, QScrollArea, QMessageBox)
from PyQt5.QtCore import Qt, QSettings
from PyQt5.QtGui import QFont
import os


class NotepadWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.current_file = None
        self.file_modified = False
        self.mdi_window = None  # 存储对QMdiSubWindow的引用
        self.init_ui()

    def init_ui(self):
        """初始化记事本界面"""
        layout = QVBoxLayout()
        self.setLayout(layout)

        # 工具栏
        toolbar_layout = QHBoxLayout()

        # 新建
        new_btn = QPushButton("新建")
        new_btn.clicked.connect(self.new_file)
        toolbar_layout.addWidget(new_btn)

        # 打开
        open_btn = QPushButton("打开")
        open_btn.clicked.connect(self.open_file)
        toolbar_layout.addWidget(open_btn)

        # 保存
        save_btn = QPushButton("保存")
        save_btn.clicked.connect(self.save_file)
        toolbar_layout.addWidget(save_btn)

        # 另存为
        save_as_btn = QPushButton("另存为")
        save_as_btn.clicked.connect(self.save_as)
        toolbar_layout.addWidget(save_as_btn)

        layout.addLayout(toolbar_layout)

        # 状态标签
        self.status_label = QLabel("新建文档")
        self.status_label.setStyleSheet("color: #666; font-size: 12px;")
        layout.addWidget(self.status_label)

        # 文本编辑区域
        self.text_edit = QTextEdit()
        self.text_edit.setFont(QFont("Consolas", 10))
        self.text_edit.textChanged.connect(self.on_text_changed)
        layout.addWidget(self.text_edit)

    def set_mdi_window(self, window):
        """设置MDI窗口引用"""
        self.mdi_window = window

    def is_modified(self):
        """检查文档是否被修改"""
        return self.file_modified

    def on_text_changed(self):
        """文本改变时"""
        self.file_modified = True
        self.update_window_title()

    def update_window_title(self):
        """更新标题"""
        if self.mdi_window is not None:
            title = self.mdi_window.windowTitle()
            if self.file_modified and not title.endswith("*"):
                self.mdi_window.setWindowTitle(title + "*")
            elif not self.file_modified and title.endswith("*"):
                self.mdi_window.setWindowTitle(title[:-1])

    def new_file(self):
        """新建文件"""
        if self.file_modified:
            reply = QMessageBox.question(
                self, '保存修改',
                '文档已修改，要保存吗？',
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                QMessageBox.Cancel
            )
            if reply == QMessageBox.Yes:
                self.save_file()
            elif reply == QMessageBox.Cancel:
                return

        self.text_edit.clear()
        self.current_file = None
        self.file_modified = False
        self.status_label.setText("新建文档")
        self.update_window_title()

    def open_file(self):
        """打开文件"""
        default_dir = os.path.expanduser("~") if not self.current_file else os.path.dirname(self.current_file)

        file_path, _ = QFileDialog.getOpenFileName(
            self, "打开文件", default_dir, "文本文件 (*.txt);;所有文件 (*)"
        )

        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    self.text_edit.setPlainText(content)

                self.current_file = file_path
                self.file_modified = False
                self.status_label.setText(f"打开ed: {file_path}")
                self.update_window_title()

            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法打开文件: {str(e)}")

    def save_file(self):
        """保存文件"""
        if self.current_file:
            try:
                with open(self.current_file, 'w', encoding='utf-8') as f:
                    f.write(self.text_edit.toPlainText())
                self.file_modified = False
                self.update_window_title()
                self.status_label.setText(f"saved: {self.current_file}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")
        else:
            self.save_as()

    def save_as(self):
        """另存为"""
        default_dir = os.path.expanduser("~") if not self.current_file else os.path.dirname(self.current_file)

        file_path, _ = QFileDialog.getSaveFileName(
            self, "另存为", default_dir, "文本文件 (*.txt);;所有文件 (*)"
        )

        if file_path:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(self.text_edit.toPlainText())

                self.current_file = file_path
                self.file_modified = False
                self.status_label.setText(f"saved: {file_path}")
                self.update_window_title()
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")